package net.wang.cloud.user.service;

import lombok.extern.slf4j.Slf4j;
import net.wang.cloud.dto.OrderDTO;
import net.wang.cloud.user.domain.Customer;
import net.wang.cloud.user.domain.PayInfo;
import net.wang.cloud.user.repo.CustomerRepo;
import net.wang.cloud.user.repo.PayInfoRepo;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class CustomerService {

    @Resource
    private CustomerRepo customerRepo;
    @Resource
    private PayInfoRepo payInfoRepo;
    @Resource
    private JmsTemplate jmsTemplate;

    @Transactional
    public Customer save() {
        Customer c = new Customer();
        System.out.println("Repo Save Start");
        Customer customer = customerRepo.save(new Customer("wang", "123456"));
        System.out.println("Repo Save End");
        if (true) {
            throw new RuntimeException("aaa");
        } else {
            return customer;
        }
    }

    public List<Customer> all() {
        return customerRepo.findAll();
    }

    @Transactional
    @JmsListener(destination = "order:pay", containerFactory = "jmsListenerContainerFactory")
    public void handleOrderPay(OrderDTO orderDTO) {
        log.info("order pay : dto = {} ", orderDTO);
        PayInfo payInfo = payInfoRepo.findByOrderId(orderDTO.getId());
        if (payInfo != null) {
            log.warn("Order already paid ");
        } else {
            Customer customer = customerRepo.findOne(orderDTO.getCustomerId());
            if (customer.getDeposit() < orderDTO.getAmount()) {
                log.error("not sufficient fund");
                orderDTO.setReason("NOT_ENOUGH_DEPOSIT");
                jmsTemplate.convertAndSend("order:ticket_error",orderDTO);
                return;
            }

            log.info("pay success");
            customer.setDeposit(customer.getDeposit() - orderDTO.getAmount());
            customerRepo.save(customer);

            payInfo = new PayInfo();
            payInfo.setOrderId(orderDTO.getId());
            payInfo.setAmount(orderDTO.getAmount());
            payInfo.setStatus("PAID");
            payInfoRepo.save(payInfo);

            orderDTO.setStatus("PAID");
            jmsTemplate.convertAndSend("order:ticket_move", orderDTO);
        }

    }
}
